package cn.jiaqiang.chatgpt.data.domain.openai.service.rule.impl.account;

import cn.jiaqiang.chatgpt.data.domain.openai.repository.IOpenAiRepository;
import cn.jiaqiang.chatgpt.data.domain.openai.service.rule.IAccountService;
import cn.jiaqiang.chatgpt.data.types.common.RedisConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;

import static cn.jiaqiang.chatgpt.data.types.common.RedisConstants.OPENAI_COUNT_TIME_PATTERN;
import static cn.jiaqiang.chatgpt.data.types.common.RedisConstants.SEPARATOR;

/**
 * User: jia-qiang
 * Date: 2024-04-04
 * Time: 21:04
 */
@Slf4j
@Component
public class ReduceAccount implements IAccountService {

    @Resource
    protected IOpenAiRepository openAiRepository;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 扣减未开户用户的额度
     */
    @Override
    public void recordUserCount(String userId) {
        // 2. 拿到当前时间, 拼接key
        SimpleDateFormat sdf = new SimpleDateFormat(OPENAI_COUNT_TIME_PATTERN);
        String currentDate = sdf.format(new Date());
        String key = RedisConstants.OPENAI_COUNT_PREFIX + SEPARATOR + currentDate + SEPARATOR + userId;

        // 访问次数限制判断
        String count = stringRedisTemplate.opsForValue().get(key);
        if (!StringUtils.hasLength(count)) {
            // 当日第一次访问, 设置为1
            stringRedisTemplate.opsForValue().set(key, "1");
            log.info("用户 userId: {} 在 {} 访问已经访问次数为: {}", userId, currentDate, 1);
            return;
        }
        // 否则直接++存起来即可.
        int visitCount = Integer.parseInt(count);
        // 次数 ++ 存到 redis
        visitCount += 1;
        stringRedisTemplate.opsForValue().set(key, visitCount + "");
        log.info("用户 userId: {} 在 {} 访问已经访问次数为: {}", userId, currentDate, visitCount);

    }

    /**
     * 扣减开户用户的额度
     */
    @Override
    public void reduceUserChatCount(String userId, String model) {
        openAiRepository.subAccountQuota(userId, model);
    }

}
